#include "EmbedText.h"
#include <coreai/embedding/embedding.h>

#include <iostream>



using namespace std;


static const char* embeded_user_query_text_file_path = "../utils/embedded_files/embedded_user_query.txt";

EmbedText::EmbedText(){
    
    session = text_embedding_create_session();

    text_embedding_init_session(session);

    
}

EmbedText::~EmbedText(){
    
    embedding_result_destroy(&result);
    embedding_model_info_destroy(info);
    text_embedding_destroy_session(&session);

}



void EmbedText::embed_str_data(string text){
    text_embedding(session, text.c_str(), &result);

    error_code = embedding_result_get_error_code(result);

    error_message = embedding_result_get_error_message(result);

    vector_result = embedding_result_get_vector_data(result);

    len = embedding_result_get_vector_length(result);

    text_embedding_get_model_info(session, &info);

    save_vector_to_file(embeded_user_query_text_file_path, vector_result, len, "w");

}


void EmbedText::embed_file_data(string file_path, const char* destination_path){

    std::ifstream file(file_path);

    // 检查文件是否成功打开
    if (!file.is_open()) {
        std::cout << "无法打开文件 " << file_path << std::endl;
    }

    string text; 
    // 逐行读取文件内容
    int index = 0;
    while (std::getline(file, text)) {

        std::cout << "\n start: \n" << index++ << std::endl;
        text_embedding(session, text.c_str(), &result);
        std::cout << "next \n";
        error_code = embedding_result_get_error_code(result);

        error_message = embedding_result_get_error_message(result);

        vector_result = embedding_result_get_vector_data(result);

        len = embedding_result_get_vector_length(result);

        text_embedding_get_model_info(session, &info);

        save_vector_to_file(destination_path, vector_result, len, "a");

    }

    file.close();

  

    
}

void EmbedText::save_vector_to_file(const char* filename, float *vector, int len, const char* w_or_a) {
    FILE *file = fopen(filename, w_or_a);
    if (file == NULL) {
        fprintf(stderr, "无法打开文件 %s 用于写入。\n", filename);
        return;
    }

    for (int i = 0; i < len; i++) {
        fprintf(file, "%f\n", vector[i]);
    }

    if (w_or_a == "a"){ // 用户的query不加这个分割符号
        fprintf(file, "|\n");
    }

    fclose(file);
}